package com.example.jpetstoreclient.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.domain.Animal;
import com.example.jpetstoreclient.domain.CartItem;
import com.example.jpetstoreclient.domain.Order;
import com.example.jpetstoreclient.domain.User;
import com.example.jpetstoreclient.persistance.OrderMapper;
import com.example.jpetstoreclient.service.AnimalService;
import com.example.jpetstoreclient.service.CartItemService;
import com.example.jpetstoreclient.service.OrderService;
import com.example.jpetstoreclient.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    AnimalService animalService;

    @Autowired
    CartItemService cartItemService;

    @Autowired
    UserService userService;

    @Override
    public CommonResponse<List<Order>> getAllOrders(int user_id) {
        User user = userService.getById(user_id);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user_id);
        List<Order> orders = list(wrapper);
        for (Order order : orders){
            int animal_id = order.getProduct_id();
            Animal animal = animalService.getById(animal_id);
            //TODO:deliver_str还没设置
            order.setPet_name(animal.getName());
            order.setUser_name(user.getUsername());
            order.setPhone(user.getPhone());
            order.setSignal_count(animal.getPrice());
            order.setTotal_count(animal.getPrice().multiply(new BigDecimal(order.getProduct_number())));
            order.setUrl(animal.getUrl());
            order.setGood_specific(animal.getGood_specific());
        }

        return CommonResponse.createForSuccess("查询所有订单",orders);


    }

    //可以优化
    @Override
    public CommonResponse<List<Order>> generateOrders(List<Integer> cart_ids,int user_id,String remark,String address) {
        List<Order> orders = new ArrayList<>();
        List<CartItem> cartItems = cartItemService.listByIds(cart_ids);
        //由CartItem生成每个order
        for(CartItem cartItem : cartItems){
            int animal_id = cartItem.getAnimal_id();
            int number = cartItem.getNumber();
            Animal animal = animalService.getById(animal_id);
            Order order = new Order(animal_id,number,false,null,false,null,remark,address,user_id);
//            //生成日期由数据库自动生成
            orders.add(order);
        }

        //提交订单时减少库存
        for(CartItem cartItem : cartItems){
            int animal_id = cartItem.getAnimal_id();
            int number = cartItem.getNumber();
            Animal animal = animalService.getById(animal_id);
            int stock = animal.getNumber();
            if(stock < number)return CommonResponse.createForError("库存不足，订单生成失败！");
            else {
                animal.setNumber(stock - number);
                animalService.updateById(animal);
            }
        }

        //保存order
        if(saveBatch(orders)){

            //清除购物车中对应商品
            cartItemService.removeByIds(cart_ids);
            return CommonResponse.createForSuccess("生成订单成功！",orders);
        }
        else{
            //恢复减少的库存
            for(CartItem cartItem : cartItems){
                int animal_id = cartItem.getAnimal_id();
                int number = cartItem.getNumber();
                Animal animal = animalService.getById(animal_id);
                int stock = animal.getNumber();
                animal.setNumber(stock + number);
                animalService.updateById(animal);
            }
            return CommonResponse.createForError("生成订单失败！");
        }
    }

    @Override
    public CommonResponse<Object> addOrder(Order order) {

        //提交订单减少库存
        int animal_id = order.getProduct_id();
        int number = order.getProduct_number();
        Animal animal = animalService.getById(animal_id);
        int stock = animal.getNumber();
        if(stock < number)return CommonResponse.createForError("库存不足，订单生成失败！");
        else {
            animal.setNumber(stock - number);
            animalService.updateById(animal);
        }

        if(save(order)) return CommonResponse.createForSuccess("生成订单成功！",order);
        else {
            //恢复减少的库存
            animal.setNumber(stock + number);
            animalService.updateById(animal);
            return CommonResponse.createForError("生成订单失败！");
        }

    }

    @Override
    public CommonResponse<Order> payOrder(int order_id) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_number",order_id).set("isPay",1);
        update(null,updateWrapper);
        Order order = getById(order_id);
        return CommonResponse.createForSuccess("付款成功！",order);

    }

    @Override
    public CommonResponse<Object> deleteOrder(int order_id) {
        if(removeById(order_id))return CommonResponse.createForSuccessMessage("删除订单成功！");
        else return CommonResponse.createForError("删除订单失败！");
    }
}
